<template>
  <div class="container">
    <TopTabs
      v-model="searchTab"
      :items="searchTabOptions"
      item-label="label"
      item-value="value"
      class="top-tabs"
    ></TopTabs>
    <div class="content">
      <keep-alive>
        <component :is="component"></component>
      </keep-alive>
    </div>
  </div>
</template>
<script setup>
import { computed, defineAsyncComponent, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useNavStore } from '@/store/nav'
import { useSearchStore } from '@/store/search'
import { TAB_TYPE } from '@/constant/search'

const TopTabs = defineAsyncComponent({ loader: () => import('@/components/tabs/TopTabs.vue') })
const TabSearch = defineAsyncComponent({ loader: () => import('@/pages/search/TabSearch.vue') })
const TabCategory = defineAsyncComponent({ loader: () => import('@/pages/search/TabCategory.vue') })
const TabFavorite = defineAsyncComponent({ loader: () => import('@/pages/search/TabFavorite.vue') })

const navStore = useNavStore()
const { searchTab, atSearchTab, atCategoryTab, atFavoriteTab } = storeToRefs(navStore)

const component = computed(() => {
  switch (searchTab.value) {
    case TAB_TYPE.SEARCH:
      return TabSearch
    case TAB_TYPE.CATEGORY:
      return TabCategory
    case TAB_TYPE.FAVORITE:
      return TabFavorite
    default:
      return null
  }
})

const accountStore = useAccountStore()
const { isLogin } = storeToRefs(accountStore)
const tabOptionsLogin = [
  { label: 'tab.search', value: TAB_TYPE.SEARCH },
  { label: 'tab.category', value: TAB_TYPE.CATEGORY },
  { label: 'tab.favorite', value: TAB_TYPE.FAVORITE },
]
const tabOptionsLogout = [
  { label: 'tab.search', value: TAB_TYPE.SEARCH },
  { label: 'tab.category', value: TAB_TYPE.CATEGORY },
]
const searchTabOptions = computed(() => (isLogin.value ? tabOptionsLogin : tabOptionsLogout))

const searchStore = useSearchStore()
const { updateViewerRouterOriginPath } = searchStore
watch([atSearchTab, atCategoryTab, atFavoriteTab], ([s, c, f]) => {
  if (s || c || f) updateViewerRouterOriginPath()
})
</script>
<style scoped lang="scss">
.container {
  height: 100%;

  .top-tabs {
    padding: 0.875rem 1rem 1rem;
  }
  .content {
    height: calc(100% - 3.275rem);
  }
}
</style>
